﻿using System;
using System.Linq;
using System.Web.Mvc;
using ePayment;
using e_TicaretSistemi.Models;

namespace e_TicaretSistemi.Controllers
{
    public class ProductController : BaseController
    {
        //Ürün Listesi, Kategoriye Göre Sıralama
        public ActionResult Index(string id, DefaultFilter filter)
        {
            IQueryable<Product> list = null;

            if (!string.IsNullOrEmpty(id))
            {
                var category = Db.Categories.Single(d => d.SeoText.Equals(id));
                ViewBag.CategoryName = category.Text;
                list = Db.Products.Where(d => d.CategoryId == category.Id);
            }
            else
            {
                list = Db.Products.AsQueryable();

            }
            // AddFilter(filter, list);
            if (filter != null)
            {
                if (!string.IsNullOrEmpty(filter.SearchString))
                {
                    list =
                        Db.Products.Where(
                            d =>
                                d.Title.Contains(filter.SearchString) || d.Model.Contains(filter.SearchString) ||
                                d.Description.Contains(filter.SearchString));
                }
                if (filter.SortDir == Enums.SortDirEnum.Asc)
                {
                    if (filter.Sort == Enums.ProductColumnEnum.Title)
                        list = list.OrderBy(d => d.Title);
                    if (filter.Sort == Enums.ProductColumnEnum.Price)
                        list = list.OrderBy(d => d.Price);
                    if (filter.Sort == Enums.ProductColumnEnum.Model)
                        list = list.OrderBy(d => d.Model);
                }
                else
                {
                    if (filter.Sort == Enums.ProductColumnEnum.Title)
                        list = list.OrderByDescending(d => d.Title);
                    if (filter.Sort == Enums.ProductColumnEnum.Price)
                        list = list.OrderByDescending(d => d.Price);
                    if (filter.Sort == Enums.ProductColumnEnum.Model)
                        list = list.OrderByDescending(d => d.Model);
                }
            }

            return View(list.ToList());
        }

        public ActionResult Detail(string id)
        {
            var product = Db.Products.SingleOrDefault(d => d.SeoText.Equals(id));
            if (product == null)
                throw new Exception("Ürün Bulunamadı.");
            return View(product);
        }

        public ActionResult Sale(int id)
        {
            var product = Db.Products.SingleOrDefault(d => d.Id.Equals(id));
            if (product == null)
                return RedirectToAction("Index");
            return View(new UserCardInfo { Product = product });
        }

        [HttpPost]
        public ActionResult Sale(UserCardInfo cardInfo)
        {
            var product = Db.Products.SingleOrDefault(d => d.Id == cardInfo.Id);
            if (product == null)
                return RedirectToAction("Index");
            if (!ModelState.IsValid)
            {
                cardInfo.Product = product;
                return View(cardInfo);
            }
            var payment = new cc5payment { host = "host" };
            //Veri Gönderilecek Adres
            payment.name = ""; //Sanal Pos Kullanıcı Adı
            payment.password = ""; //Sanal Pos Sifre
            payment.clientid = ""; //Mağaza id'niz
            payment.orderresult = 0; //1 Olunca Test İşlemi, 0 Olunca Gercek İşlem
            payment.cardnumber = cardInfo.CardNumber; //Kredi Kartı Numarası
            payment.expmonth = cardInfo.ExpMonth.ToString(); //Kredi Kartı Bitiş Ayı
            payment.expyear = cardInfo.ExpYear.ToString(); //Kredi Kartı Bitişi Yılı
            payment.cv2 = cardInfo.SecurityNumber; //Kredi Kartı CVC Numarası
            payment.currency = "949"; //TL Birimi İçin 949
            payment.ip = Request.ServerVariables["REMOTE_ADDR"]; //IP Adresi
            payment.subtotal = ((product.Price * product.Kdv) / 100) + product.Price.ToString(); //Çekilecek Miktar
            payment.taksit = "1"; //Taksit Miktarı

            string bankaSonuc = payment.processorder(); //Methot Çağrılır
            string bankaHata = payment.errmsg; //Dönen Hata Mesajı
            string bankaOid = payment.oid; //Dönen İşlem Sonucu
            string bankaAppr = payment.appr; //Dönen İşlem Sonucu
            string bankaProv = payment.code; //Dönen Provizyon Numarası

            if (bankaSonuc == "1")
            {
                if (bankaAppr == "Approve") //Ödeme İşlemi tamam
                {
                    ViewBag.Result = "Ödeme İşlemi Başarı ile Tamamlandı.";
                }
                else if (bankaAppr == "Declined") //Ödeme İşlemi Reddedildi
                {
                    ViewBag.Result = "Banka Ödemeyi Reddetti";
                }
                else  //İrtibat Kurulamadı
                {
                    ViewBag.Result = "Banka ile İletişim Kurulamadı.";
                }
            }
            var sale = new Sale
            {
                CargoPrice = 20,
                CustomerId = CurrentCustomer.Id,
                ProductId = cardInfo.Id,
                RecordDate = DateTime.Now,
                SaleState = (short)Enums.SaleState.PendingCheck,
                BillAdress = cardInfo.BillAdress,
                DeliveryAdress = cardInfo.DeliveryAdress
            };
            Db.Sales.InsertOnSubmit(sale);
            var basket = Db.CustomerOfBaskets.SingleOrDefault(d => d.CustomerId == CurrentCustomer.Id && d.ProductId == product.Id);
            if (basket != null)
                Db.CustomerOfBaskets.DeleteOnSubmit(basket);
            Db.SubmitChanges();
            return RedirectToAction("Index");
        }
    }
}